<template>
  <el-form :rules="FormRules" ref="dataForm" :model="Form" label-width="120px" v-loading="listLoading" >
    <el-form-item>
      <div class="el-card_tit">
        <span>基本信息</span>
      </div>
    </el-form-item>
    <el-form-item label="选择方案模板" prop="fanganmuban">
      <el-select v-model="Form.fanganmuban" placeholder="选择方案模板" :disabled="isDisabled">
        <el-option v-for="item in planModelOptions" :key="item.fanganmuban" :label="item.planModelName" :value="item.fanganmuban"></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="最长运输时间" prop="transtime" >
      <el-input-number :disabled="isDisabled" v-model="Form.transtime" :precision="1" :min="0" label="时间"/>&nbsp;h
    </el-form-item>
    <el-form-item label="选择蓄冷剂组" prop="xulengjizu">
      <el-select v-model="Form.xulengjizu" placeholder="选择蓄冷剂组" :disabled="isDisabled">
        <el-option v-for="item in refrigerantOptions" :key="item.xulengjizu" :label="item.refrigerantName" :value="item.xulengjizu"></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="温度范围：">
      <span>
        <el-input-number v-model="Form.lowtemperature" :precision="2" :step="0.1" label="最低温度：" :disabled="isDisabled"/>&nbsp;℃
      </span>
      <span>到</span>
      <span>
        <el-input-number v-model="Form.hightemperature" :precision="2" :step="0.1" label="最高温度：" :disabled="isDisabled"/>&nbsp;℃
      </span>
    </el-form-item>
    <el-form-item label="本次验证类型：">满载</el-form-item>
    <el-form-item label="验证周期：" prop="verifytype">
      <el-radio-group v-model="Form.verifytype" :disabled="isDisabled">
        <el-radio :label="1">冬季</el-radio>
        <el-radio :label="2">夏季</el-radio>
        <el-radio :label="3">使用前</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item label="冷源：" prop="coldsource">
      <el-input v-model="Form.coldsource" :disabled="isDisabled"/>
    </el-form-item>
    <el-form-item label="验证参与人员：">
      <el-button type="primary" @click="handleParticipants">查看</el-button>&nbsp;&nbsp;(点击勾选验证参与成员)
    </el-form-item>
    <el-form-item>
      <div class="el-card_tit">
        <span>无线温湿度传感器设置</span>
      </div>
    </el-form-item>
    <el-form-item label="开箱记录间隔：">
      <el-input-number v-model="Form.openinterval" :min="0" label="开箱记录间隔" :disabled="isDisabled"/>&nbsp;min
    </el-form-item>
    <el-form-item label="保温记录间隔：">
      <el-input-number v-model="Form.recordinterval" :min="0" label="保温记录间隔" :disabled="isDisabled"/>&nbsp;min
    </el-form-item>
    <el-form-item>
      <div class="el-card_tit">
        <span>验证实施时间</span>
      </div>
    </el-form-item>
    <el-form-item label="计划测试时间：" prop="testtime">
      <el-date-picker v-model="Form.testtime" type="date" placeholder="请选择时间" :disabled="isDisabled"/>
    </el-form-item>
    <el-form-item>
      <el-button :disabled="checkPermission(['engineer'])? false : true" v-show="saveShow" @click="saveForm('dataForm')">保存</el-button>
      <!-- <el-button :disabled="checkPermission(['engineer'])? false : true" type="primary" @click="submitForm('dataForm')">提交</el-button> -->
      <el-button type="warning" @click="generateForm(Form)" :loading="generateLoading" >生成文档</el-button>
    </el-form-item>
  </el-form>
</template>
<script>
import checkPermission from "@/utils/permission"; // 权限判断函数
import { getFanganList } from "@/api/fangan";
import { getTaskData } from "@/api/task";
import { getProjectData, updateProjectState } from "@/api/project";
import { getGeneratePlan } from "@/api/project";
import { getRefrigerantList } from "@/api/incubator";
import { getProjectDataInfo, updateProjectData } from "@/api/projectData";

export default {
  name: "incubatorStep1",
  props: ["getId"],
  data() {
    return {
      planModelOptions: [],
      refrigerantOptions: [],
      customerId: "",
      listLoading: false,
      generateLoading: false,
      saveShow: true,
      isDisabled: false,
      Form: {
        fanganmuban: null,
        transtime: 0,
        xulengjizu: null,
        lowtemperature: 0,
        hightemperature: 0,
        verifytype: 1,
        coldsource: "",
        openinterval: 0,
        recordinterval: 0,
        testtime: new Date()
      },
      FormRules: {
        fanganmuban: [
          { required: true, message: "请选择模板方案", trigger: "change" }
        ],
        transtime: [
          { required: true, message: "请输入最长运输时间", trigger: "blur" }
        ],
        xulengjizu: [
          { required: true, message: "请选择蓄冷剂组", trigger: "change" }
        ],
        lowtemperature: [
          { required: true, message: "请输入最低温度", trigger: "blur" }
        ],
        hightemperature: [
          { required: true, message: "请输入最高温度", trigger: "blur" }
        ],
        verifytype: [
          { required: true, message: "请选择验证周期", trigger: "change" }
        ],
        coldsource: [
          { required: true, message: "请输入冷源", trigger: "blur" }
        ],
        openInterval: [
          { required: true, message: "请输入开箱记录间隔", trigger: "blur" }
        ],
        recordinterval: [
          { required: true, message: "请输入保温记录间隔", trigger: "blur" }
        ],
        testtime: [
          {
            type: "date",
            required: true,
            message: "请填写验证实施时间",
            trigger: "change"
          }
        ]
      }
    };
  },
  created() {
    this.getPlanModel();
    this.getRefrigerant();
    this.getData();
  },

  methods: {
    checkPermission,

    //获取模板列表
    async getPlanModel() {
      //获取主项目customerId
      const { data } = await getProjectData({ projectId: this.getId })
      const { tid } = data
      const {customerId} = await getTaskData({ taskId: tid })
      this.customerId = customerId
      //获取方案模板
      const result = await getFanganList({ customerId: this.customerId, deviceType: 1 })
      this.planModelOptions = result.data.map(item => {
        return { fanganmuban: item.pid, planModelName: item.name };
      });
    },

    //获取蓄冷剂组列表
    async getRefrigerant() {
      //获取子项目deviceId
      const { data } = await getProjectData({ projectId: this.getId })
      const { deviceId } = data
      let result = await getRefrigerantList({ incubatorId: deviceId })
      this.refrigerantOptions = result.data.map(item => {
        return { xulengjizu: item.id, refrigerantName: item.name };
      });
    },

    //获取子项目进度准备阶段参数
    async getData() {
      this.listLoading = true;
      if (checkPermission(["manager"])) {
        this.isDisabled = true;
      }
      const { data } = await getProjectDataInfo({ projectId: this.getId })
        for (const item of data) {
          this.Form[item.name] = item.genre == "point" || item.genre == "int" ? Number(item.value) : item.value;
        }
      this.listLoading = false;
    },
    //保存--表格不做验证
    saveForm() {
      this.listLoading = true;
      this.Form.testtime = new Date(this.Form.testtime);
      let list = [];
      //将form对象转成数组
      for (const key of Object.keys(this.Form)) {
        list.push({ projectId: this.getId, name: key, value: this.Form[key] });
      }
      updateProjectData({ list }).then(_ => {
        this.getData();
        this.listLoading = false;
        this.$notify({
          title: "成功",
          message: "保存成功",
          type: "success",
          duration: 2000
        });
      });
    },
    //提交--表格做验证
    // submitForm(formName) {
    //   this.Form.testtime = new Date(this.Form.testtime);
    //   this.$refs[formName].validate(valid => {
    //     if (valid) {
    //       this.listLoading = true;
    //       let list = [];
    //       //将form对象转成数组
    //       for (const key of Object.keys(this.Form)) {
    //         list.push({
    //           projectId: this.getId,
    //           name: key,
    //           value: this.Form[key]
    //         });
    //       }
    //       updateProjectData({ list }).then(response => {
    //         this.getData();
    //         this.$notify({
    //           title: "成功",
    //           message: "表单提交成功",
    //           type: "success",
    //           duration: 2000
    //         });
    //         updateProjectState({ pid: this.getId, state: 32 }).then(_ => {
    //           this.$emit("changeState");
    //         });
    //         this.saveShow = false;
    //         this.listLoading = false;
    //       });
    //     } else {
    //       console.log("提交失败!!");
    //       return false;
    //     }
    //   });
    // },
    //生成word文档
    generateForm() {
      
      this.Form.testtime = new Date(this.Form.testtime);
      this.$refs["dataForm"].validate(async valid => {
        if (valid) {
          this.generateLoading = true;
          let list = [];
          //将form对象转成数组
          for (const key of Object.keys(this.Form)) {
            list.push({
              projectId: this.getId,
              name: key,
              value: this.Form[key]
            });
          }
          await updateProjectData({ list })
          this.getData();
          // 更改项目状态
          await updateProjectState({ pid: this.getId, state: 32 })
          this.$emit("changeState");
          const {data} = await getGeneratePlan({ projectId: this.getId })
            this.generateLoading = false;
            this.$confirm("立即下载", "生成成功", {
              type: "warning"
            })
            .then(() => {
              window.open(data);
            })
            .catch(() => {
              this.$message({
                type: "info",
                message: "已取消下载"
              });
            });
      
        }
      });
    },

    handleParticipants() {
      let routeData = this.$router.resolve({
        path: "/task/project/progress/participants/" + this.getId
      });
      window.open(routeData.href, "_blank");
    }
  }
};
</script>
